package sharefile

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"io"
	"log"
	"net/http"
	"oa-rest/common"
	"oa-rest/models/message"
	"path/filepath"
	"strings"
)

func ShareFileHandler(c *gin.Context) {
	// 获取当前用户（发送者）
	username := c.GetString("username")
	realName := c.GetString("realName")
	if realName == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
		return
	}

	// 获取来源参数，判断是普通文件上传还是文档库文件分享
	source := c.PostForm("source")
	isDocumentLibrary := source == "document_library"
	
	var fileUrl string
	var fileName string
	var contentType string

	if isDocumentLibrary {
		// 文档库文件分享 - 直接使用提供的URL
		fileUrl = c.PostForm("fileUrl")
		fileName = c.PostForm("fileName")
		fileId := c.PostForm("fileId")
		
		if fileUrl == "" || fileName == "" || fileId == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "文档库文件信息不完整"})
			return
		}
		
		// 从文档库获取文件信息（这里简化处理，实际可能需要查询数据库）
		contentType = "application/octet-stream" // 默认类型
		
		log.Printf("文档库文件分享: fileId=%s, fileName=%s, fileUrl=%s", fileId, fileName, fileUrl)
	} else {
		// 普通文件上传分享
		// 解析multipart form
		err := c.Request.ParseMultipartForm(32 << 20) // 32MB max
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// 获取文件
		file, header, err := c.Request.FormFile("file")
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "File is required"})
			return
		}
		defer file.Close()

		// 读取文件内容
		data, err := io.ReadAll(file)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		// 生成唯一对象名称
		ext := filepath.Ext(header.Filename)
		objectName := uuid.New().String() + ext
		fileName = header.Filename
		contentType = header.Header.Get("Content-Type")

		// 上传到S3 sharefile bucket
		fileUrl, err = common.UploadSharefile(objectName, data, contentType)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Upload failed: " + err.Error()})
			return
		}
	}

	// 获取其他参数
	recipientsStr := c.PostForm("recipients")
	description := c.PostForm("description")

	// 解析接收者列表（假设逗号分隔）
	recipients := strings.Split(recipientsStr, ",")
	if len(recipients) == 0 || (len(recipients) == 1 && recipients[0] == "") {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Recipients are required"})
		return
	}

	// 获取数据库连接
	db, err := common.ConnectDb()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "DB connection failed: " + err.Error()})
		return
	}

	// 对每个接收者插入记录
	for _, recipient := range recipients {
		if recipient == "" {
			continue
		}
		
		// 插入sharefile记录
		sf := &ShareFile{
			SharerId:    username,
			RecipientId: recipient,
			FileUrls:    []string{fileUrl},
			Content:     description,
		}
		_, err = db.Insert(sf)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert sharefile: " + err.Error()})
			return
		}

		// 插入message通知
		msg := &message.Message{
			Sender:   realName,
			Receiver: recipient,
			RefName:  fileName,
			RefUrl:   fileUrl,
			Type:     2, // 2 => 文件分享通知
			Status:   1,
			Priority: 1,
			RefId:    sf.Id,
		}
		_, err = db.Insert(msg)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert message: " + err.Error()})
			return
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "File shared successfully",
		"url": fileUrl,
		"source": source,
		"fileName": fileName,
	})
}
